<template>
  <div class="page-container">
    <div class="container">
      <page-form :model="form" ref="formRef" :rules="rules" layout="vertical" :class="{ checkInfo: form.ifOpenCheck }">
        <!-- 付款单模块 -->
        <card title="付款单" :showDivider="false">
          <!-- 根据是否审批变更页面表格布局 -->
          <formContent v-if="form.ifOpenCheck" @getRefCarInfoList="getRefCarInfoList" />
          <formContent v-else @getRefCarInfoList="getRefCarInfoList" />
        </card>
        <a-divider style="margin: 0 0 10px" />
        <!-- 支出费用信息 -->
        <div class="fee-container">
          <div class="content-title">
            <h3>支出总额：</h3>
            <div class="fee-text">
              <div
                >共<span class="link">{{ form.feeList.length }}</span
                >笔</div
              >
              <span class="line">|</span>
              <div
                ><span class="link">{{ form.amount }}</span
                >元</div
              >
            </div>
          </div>
          <!-- 费用明细模块 -->
          <div class="fee-content">
            <feeItem
              v-for="(infoItem, index) in form.feeList"
              :key="infoItem.key"
              :fieldFee="`feeList.${index}.`"
              :info="infoItem"
              :feeIndex="index"
              @changeFee="changeFee"
            />
            <div class="btn" v-if="form.feeList.length < 10">
              <a-button type="primary" @click="addFee">
                <template #icon>
                  <icon-plus />
                </template>
                添加
              </a-button>
            </div>
          </div>
        </div>
        <page-form-row>
          <!-- 申请备注 -->
          <page-form-item label="申请备注" size="1">
            <a-textarea placeholder="请输入" :max-length="200" v-model="form.remark" allow-clear auto-size />
            <!-- <i-input placeholder="请输入" v-model="form.remark" :maxLength="200" /> -->
          </page-form-item>
        </page-form-row>
        <!-- 收款方信息 -->
        <card title="收款方信息" :showDivider="false">
          <page-form-row>
            <!-- 收款方类型 -->
            <page-form-item label="收款方类型" field="collectType" size="1/2">
              <a-select placeholder="请选择" v-model="form.collectType" @change="changCollectType">
                <a-option v-for="item in dict.collectTypeEnum" :key="item.value" :value="item.value" :label="item.label" />
              </a-select>
            </page-form-item>
            <!-- 收款方名称 -->
            <page-form-item label="收款方名称" field="collectId" size="1/2">
              <template #label-extra>
                <a-link v-if="!form.collectType" class="disabled-btn" @click="addDisabledText(1)"> + 新增 </a-link>
                <a-link class="add-btn" v-else @click="addCollection"> + 新增 </a-link>
              </template>
              <i-input v-if="!form.collectType" disabled placeholder="请选择" />
              <remote-select
                v-if="form.collectType == '2'"
                v-model="form.collectId"
                :params="{
                  id: form.collectId,
                }"
                placeholder="请选择"
                @change="changePeerFn"
                type="supplier_allth"
              />
              <remote-select
                v-if="form.collectType == '3'"
                v-model="form.collectId"
                :params="{
                  id: form.collectId,
                }"
                placeholder="请选择"
                @change="changeSupplierFn"
                @focus="focusSupplierFn"
                type="supplier_list"
              />
            </page-form-item>
          </page-form-row>
          <!-- 收款账号 -->
          <page-form-item label="收款账号" field="collectBackId" size="1">
            <template #label-extra>
              <a-link v-if="!form.collectId" class="disabled-btn" @click="addDisabledText(2)"> + 添加收款账号 </a-link>
              <a-link class="add-btn" v-else @click="addAccount"> + 添加收款账号 </a-link>
            </template>
            <a-select
              :disabled="!form.collectId"
              placeholder="请选择"
              v-model="form.collectBackId"
              @change="changeBankInfo"
              popup-container="body"
              :trigger-props="{ updateAtScroll: true }"
            >
              <a-option v-for="item in backInfoList" :key="item.id" :value="item.id" :label="getLabel(item)" />
            </a-select>
          </page-form-item>
        </card>
      </page-form>

      <!-- 审批人模块 -->
      <form-approval-content v-if="form.ifOpenCheck" />
    </div>
    <!-- 新增同行收款方名称弹框 -->
    <add-peer-modal ref="addPeerRef" @addNameOk="addNameOk" />

    <!-- 新增供应商收款方名称弹框 -->
    <add-supplier-modal ref="addSupplierRef" @addNameOk="addNameOk" />

    <!-- 银行账户弹框 -->
    <account-modal ref="accountModalRef" @addOk="addOk" />
  </div>
  <!-- 底部 footer -->
  <page-form-footer :ok-loading="okLoading" @ok="submitFn" />
</template>

<script setup name="OperateCostPayForm">
  import { ref, reactive, provide, onMounted } from 'vue'
  import { Message } from '@arco-design/web-vue'
  import { usePageDict } from '@/hooks/useDict'
  import dayjs from 'dayjs'
  import feeItem from '../components/feeItem.vue'
  import addPeerModal from '../components/add-peer-modal.vue'
  import addSupplierModal from '../components/add-supplier-modal.vue'
  import accountModal from '../components/account-modal.vue'
  import formContent from '../components/formContent.vue'
  import formApprovalContent from '../components/form-approval-content.vue'
  import { getApprovalSetings } from '@/api/system/approvalSetings'
  import { getLoginUserInfo } from '@/api/user'
  import {
    editCostApi,
    getPeerList,
    getSupplierList,
    getCostDetailApi,
    getNewCostDetailApi,
    getShortCarRecord,
    getLongCarRecord,
    getCheckHistoryApi,
  } from '@/api/business/operateCost'
  import { getDetails } from '@/api/business/workorder'
  import useNavigate from '@/hooks/useNavigate'
  import { useRoute } from 'vue-router'

  const route = useRoute()
  const routeQuery = route.query
  const routeParams = route.params
  const { navigateBack, navigateClose } = useNavigate()

  const dict = usePageDict('getCostEnums')
  const form = ref({
    refCostType: 1,
    amount: 0,
    ifOpenCheck: 0,
    workInfo: '-',
    feeOrgName: '-',
    memberInfo: '-',
    feeList: [
      {
        amount: null,
        item: '',
        occurTime: dayjs().format('YYYY-MM-DD HH:mm:ss'),
        fileIdList: [],
        carModel: '-',
      },
    ],
    checkFlowList: [],
  })
  // 关联工单，关联业务单 费用明细车牌号，车型数据
  const refCarInfoList = ref([])

  // 暴露给子组件 form 对象
  provide('form', form)

  provide('refCarInfoList', refCarInfoList)

  // 表单规则
  const rules = reactive({
    refCostType: { required: true, message: '请选择关联单据类型' },
    workType: { required: true, message: '请选择关联工单类型' },
    businessType: { required: true, message: '请选择关联业务类型' },
    businessId: { required: true, message: '请选择关联业务单号' },
    workId: { required: true, message: '请选择关联工单号' },
    feeOrgId: { required: true, message: '请选择费用产生门店' },
    collectType: { required: true, message: '请选择收款方类型' },
    collectId: { required: true, message: '请选择收款方名称' },
    collectBackId: { required: true, message: '请选择收款方信息' },
  })

  const getLabel = (item) => {
    if (item.inExpWay === 1) {
      return `${item.inExpWayName} | ${item.bankCardNumber} | ${item.bank}`
    } else {
      return `${item.inExpWayName} | ${item.bankCardNumber}`
    }
  }

  // 获取业务单和工单车辆信息列表
  const getRefCarInfoList = () => {
    let businessId = form.value.businessId
    let workId = form.value.workId
    if (businessId && form.value.refCostType == 2) {
      getBusinessCarList(businessId)
    }
    if (workId) {
      getWorkCarList(workId)
    }
  }
  // 获取业务单车辆数据
  const getBusinessCarList = (id) => {
    let fetch = form.value.businessType == 1 ? getShortCarRecord : getLongCarRecord
    fetch({ id: id }).then((res) => {
      refCarInfoList.value = res.result
      if (res.result?.length == 1) {
        // 费用信息回填车牌号和车型名称
        form.value.feeList.forEach((i) => ((i.carId = res.result[0].carId), (i.carModel = res.result[0].carModelName)))
      }
    })
  }
  // 获取工单车辆数据
  const getWorkCarList = (id) => {
    getDetails({ id: id }).then((res) => {
      let result = res.result
      refCarInfoList.value = []
      if (result.workType == 1 || result.workType == 2) {
        if (result.carLicenseNo) {
          refCarInfoList.value = [
            {
              carId: result.carId,
              modelId: result.carModelId,
              modelName: result.carModelName,
              licenseNo: result.carLicenseNo,
            },
          ]
          // 费用信息回填车牌号和车型名称
          form.value.feeList.forEach((i) => ((i.carId = result.carId), (i.carModel = result.carModelName)))
        }
      } else {
        if (result.carLicenseNo) {
          refCarInfoList.value.push({
            carId: result.carId,
            modelId: result.carModelId,
            modelName: result.carModelName,
            licenseNo: result.carLicenseNo,
          })
        }
        if (result.replacedCarLicenseNo) {
          refCarInfoList.value.push({
            carId: result.replacedCarId,
            modelId: result.replacedCarModelId,
            modelName: result.replacedCarModelName,
            licenseNo: result.replacedCarLicenseNo,
          })
        }
      }
    })
  }

  // 新增费用明细
  const addFee = () => {
    if (form.value.feeList.length < 10) {
      form.value.feeList.push({
        item: null,
        amount: '',
        occurTime: dayjs().format('YYYY-MM-DD HH:mm:ss'),
        fileIdList: [],
        carModel: '-',
      })
      getRefCarInfoList()
    }
  }
  // 更改费用
  const changeFee = (val) => {
    let sum = 0
    val.forEach((item) => {
      sum += item.amount || 0
    })

    form.value.amount = sum
  }

  // 获取员工信息
  const getUserInfo = () => {
    getLoginUserInfo({}).then((res) => {
      if (res.code == 200) {
        const data = res.result
        form.value.loginUserId = data.id
      }
    })
  }
  // 最新配置审批人数据
  const newFlowList = ref([])
  // 最新审批开关
  const isNewOpenCheck = ref()
  // 获取审批人数据
  const getApprovalSet = () => {
    getApprovalSetings({
      type: 1,
    }).then((res) => {
      if (res.code == 200) {
        // 默认无填充1个空值
        const flowList = res.result.flowList
        if (!flowList || flowList.length == 0) {
          res.result.flowList = [{ id: 0, post: undefined }]
        }
        newFlowList.value = flowList.map((item) => {
          return {
            post: item.post,
            postName: item.postName,
          }
        })
        isNewOpenCheck.value = res.result.ifOpen
        form.value.checkFlowList = newFlowList.value
        form.value.ifOpenCheck = isNewOpenCheck.value
        if (!routeParams.id) {
          getCheckHistory()
        }
      }
    })
  }
  // 更改收款方类型
  const changCollectType = () => {
    form.value.collectId = ''
    form.value.collectBackId = null
  }
  // 获取同行，供应商信息
  const peerSupplierData = ref({})

  // 选择同行
  const changePeerFn = (val, option) => {
    form.value.collectId = val
    peerSupplierData.value = option
    if (val) {
      getPeerBankData(val)
    }
    form.value.collectBackId = null
  }
  // 选择供应商
  const changeSupplierFn = (val, option) => {
    form.value.collectId = val
    peerSupplierData.value = option
    if (val) {
      getSupplierBankData(val)
    }
    form.value.collectBackId = null
  }
  // 输入框获取焦点重置供应商收款方名称列表数据
  const focusSupplierFn = () => {
    form.value.collectId = ''
  }
  // 新增同行，供应商收款名称信息
  const addNameOk = (val) => {
    if (form.value.collectType == '2') {
      form.value.collectId = val.id
      getPeerBankData(val.id)
    } else {
      form.value.collectId = val
      getSupplierBankData(val)
    }
  }
  // 获取银行账户信息
  const backInfoList = ref([])
  // 获取同行银行账户信息
  const getPeerBankData = (id) => {
    getPeerList({ id }).then((res) => {
      const result = res.result
      console.log(result, '同行账户信息')
      peerSupplierData.value = result
      backInfoList.value = result.backInfoList || []
    })
  }
  // 获取供应商银行账户信息
  const getSupplierBankData = (id) => {
    getSupplierList({ id }).then((res) => {
      const result = res.result
      peerSupplierData.value = result
      backInfoList.value = result.backInfoList || []
    })
  }

  // 新增收款方名称信息
  const addPeerRef = ref()
  const addSupplierRef = ref()
  const addCollection = () => {
    if (form.value.collectType == '2') {
      addPeerRef.value.show()
    } else {
      addSupplierRef.value.show()
    }
  }
  // 选中收款账号信息
  const changeBankInfo = (val) => {
    if (val) {
      backInfoList.value.map((item) => {
        if (item.id === val) {
          form.value.collectInExpWay = item.inExpWay
          form.value.collectInExpWayName = item.inExpWayName
          form.value.collectCard = item.bankCardNumber
          form.value.collectBackName = item.bank
          // form.value.collectBackProvinceCode = item.provinceCode
          // form.value.collectBackCityCode = item.cityCode
        }
      })
    } else {
      form.value.collectInExpWay = null
      form.value.collectInExpWayName = null
      form.value.collectCard = null
      form.value.collectBackName = null
      // form.value.collectBackProvinceCode = null
      // form.value.collectBackCityCode = null
    }
  }
  // 新增银行账户
  const accountModalRef = ref()
  const addAccount = () => {
    console.log(peerSupplierData.value, 'peerSupplierData')
    console.log(backInfoList.value, 'backInfoList')
    if (backInfoList.value?.length < 10) {
      let payOrderType = form.value.collectType == '2' ? 'peerOrder' : 'supplierOrder'
      accountModalRef.value.open(payOrderType, peerSupplierData.value)
    } else {
      Message.warning(`银行账户已达上限，无法添加`)
    }
  }
  const getBankData = () => {
    if (form.value.collectType == '2') {
      getPeerBankData(form.value.collectId)
    } else {
      getSupplierBankData(form.value.collectId)
    }
  }
  // 添加银行账户成功
  const addOk = () => {
    getBankData()
  }
  // 未选择收款方类型和收款方名称时新增
  const addDisabledText = (val) => {
    if (val == 1) {
      Message.warning('请先选择收款方类型。')
    } else {
      Message.warning('请先选择收款方名称。')
    }
  }
  // 确认事件
  const formRef = ref()
  const okLoading = ref(false)
  const submitFn = () => {
    formRef.value.validate((error) => {
      if (!error) {
        okLoading.value = true
        form.value.costType = 2
        if (routeQuery.type == 'againType') {
          form.value.id = ''
          form.value.ifReApply = 1
        }
        editCostApi({ ...form.value })
          .then((res) => {
            Message.success(res.message)
            if (routeQuery.page == 'workOrder') {
              navigateClose()
              return
            }
            navigateBack()
          })
          .finally(() => {
            okLoading.value = false
          })
      }
    })
  }
  // 获取详情
  const getDetailInfo = (id) => {
    form.value.id = id
    let fetch = routeQuery.type == 'againType' ? getNewCostDetailApi : getCostDetailApi
    fetch({ id: id }).then((res) => {
      form.value = res.result
      form.value.feeList.map((i) => {
        i.occurTime = dayjs(i.occurTime).format('YYYY-MM-DD HH:mm:ss')
        i.item = i.item ? Number(i.item) : null
      })
      getBankData()
      form.value.workInfo = form.value.businessTypeName + form.value.businessCode || '-'
      form.value.memberInfo = form.value.memberName + form.value.memberPhone || '-'
      let detailFlowList = res.result.checkFlowList.map((item) => {
        return {
          post: item.post,
          postName: item.postName,
        }
      })
      // 重新申请，比较详情和配置审批流岗位及层级，相同取详情里面的，不同取配置最新的
      if (routeQuery.type == 'againType') {
        form.value.ifOpenCheck = isNewOpenCheck.value
        if (JSON.stringify(detailFlowList) == JSON.stringify(newFlowList.value) && isNewOpenCheck.value) {
          form.value.checkFlowList = res.result.checkFlowList
        } else {
          form.value.checkFlowList = newFlowList.value
        }
      }
      // 修改时，工单号列表参数取自申请人id
      form.value.loginUserId = form.value.applyStaffId

      if (form.value.collectType == '2') {
        getPeerList({ id: form.value.collectId }).then((val) => {
          const result = val.result
          backInfoList.value = result.backInfoList || []
          form.value.collectBackId = backInfoList.value?.find((i) => i.id == form.value.collectBackId) ? form.value.collectBackId : ''
        })
      } else {
        getSupplierList({ id: form.value.collectId }).then((val) => {
          const result = val.result
          backInfoList.value = result.backInfoList || []
          form.value.collectBackId = backInfoList.value?.find((i) => i.id == form.value.collectBackId) ? form.value.collectBackId : ''
        })
      }
      // 获取费用车辆信息
      getRefCarInfoList()
    })
  }
  // 查询审批流程历史
  const getCheckHistory = () => {
    getCheckHistoryApi().then((res) => {
      form.value.checkFlowList = res.result.length > 0 ? res.result : newFlowList.value
    })
  }
  onMounted(() => {
    getUserInfo()
    if (routeParams.id) {
      getDetailInfo(routeParams.id)
    }
    if (routeQuery.costParams) {
      let costData = JSON.parse(routeQuery.costParams)
      form.value.workType = costData.workType
      form.value.workId = costData.id
      form.value.workCode = costData.workCode
      form.value.workInfo = (costData.refType == 1 ? '短租' : '长租') + costData.refCode || '-'
      form.value.memberInfo = costData.memberName + costData.memberPhone || '-'
      form.value.businessType = costData.refType
      form.value.businessId = costData.refId
      form.value.businessCode = costData.refCode
      form.value.feeOrgId = costData.siteId
      form.value.feeSiteId = costData.siteId
      form.value.feeOrgName = costData.siteName
    }
    if (routeQuery.orderParams) {
      let orderData = JSON.parse(routeQuery.orderParams)
      form.value.refCostType = orderData.refCostType
      form.value.businessType = orderData.businessType
      form.value.businessId = orderData.businessId
      form.value.businessCode = orderData.businessCode
      form.value.memberInfo = orderData.memberName + orderData.memberPhone || '-'
      form.value.feeOrgId = orderData.feeOrgId
      form.value.feeSiteId = orderData.feeOrgId
      form.value.feeOrgName = orderData.feeOrgName
    }
    getApprovalSet()

    // 获取费用车辆信息
    getRefCarInfoList()
    // 运营成本增加时，默认关联单据类型为业务单
    if (routeQuery.page == 'operateCost') form.value.refCostType = 2
  })
</script>

<style lang="less" scoped>
  .container {
    display: flex;
    max-width: 100%;
  }
  .checkInfo {
    width: calc(100% - 440px) !important;
  }
  .fee-content {
    display: flex;
    flex-direction: column;
    justify-content: center;
    .btn {
      text-align: center;
    }
  }
  .content-title {
    display: flex;
    align-items: center;
    h3 {
      font-size: 16px;
      font-weight: 600;
      color: #1d2129;
    }
    .fee-text {
      display: flex;
      align-items: center;
    }
    .line {
      margin-left: 10px;
    }
    .link {
      font-size: 20px;
      margin: 0 10px;
      color: #1890ff;
    }
  }
  .add-btn {
    color: rgba(24, 144, 255, 1);
  }
  .disabled-btn {
    color: #95d6ff;
  }
</style>
